package models

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
)

//id, title, pq_test_category_id, pq_user_id, module_type, test_type, is_done, last_stop_time, created_time, updated_time, state
type PqCsSimuLibrary struct {
	Id int `json:"id"`
	Title string `json:"title"`
	PqTestCategoryId int `json:"pq_test_category_id"`
	PqUserId int `json:"user_id"`
	ModuleType int `json:"module_type"`
	TestType int `json:"test_type"`
	IsDone int `json:"is_done"`
	State int `json:"state"`
	LastStopTime int `json:"last_stop_time"`
	SimuType int `json:"simu_type"`
	LibraryId int `json:"library_id"`
	BaseModel
}
func (this PqCsSimuLibrary) GetOne(simu_library_id string) ([]orm.Params){
	var nodes []orm.Params
	model := GetSlaveDb()
	model.Raw(`
	select * from pq_cs_simu_library where id = ?
	`,simu_library_id).Values(&nodes)
	return nodes
}
func (this PqCsSimuLibrary) UpdateOne(simu_library_id string,ups orm.Params) bool{
	master := GetMasterDb()
	_,err := master.QueryTable("pq_cs_simu_library").Filter("id",simu_library_id).Update(ups)
	if err != nil {
		beego.Error(err)
		return false
	}
	return true
}
func (this PqCsSimuLibrary) GetSimuItems(simu_library_id string) ([]orm.Params){
	var nodes []orm.Params
	model := GetSlaveDb()
	model.Raw(`
	select ti.*,tl.body,tl.answer_data,tl.score,tl.pq_test_point_category_id,tl.analysis,tl.pq_cs_test_library_id,tl.pq_test_point_category_id,pc.title as point_title,tl.pq_cs_test_resource_id from pq_cs_simu_item_connection as ti
	inner join pq_cs_test_item as tl on tl.id = ti.pq_cs_test_item_id
	inner join pq_test_point_category pc on pc.id=tl.pq_test_point_category_id
	where ti.pq_cs_test_simu_library_id = ? limit ?
	`,simu_library_id,200).Values(&nodes)
	return nodes
}

func (this PqCsSimuLibrary) ListMySimuList(q ...interface{}) ([]orm.Params,interface{}) {
	var nodes []orm.Params
	model := GetSlaveDb()
	_, _ = model.Raw(`
	select SQL_CALC_FOUND_ROWS ti.* from pq_cs_simu_library ti
	where ti.state > -1 and ti.pq_user_id = ?
	order by ti.created_time desc
	limit ?,?
	`, q).Values(&nodes)
	var maps []orm.Params
	model.Raw(`
	select count('ti.*') as amount from pq_cs_simu_library ti
	where ti.state > -1 and ti.pq_user_id = ?
	`,q[0]).Values(&maps)
	//beego.Warning(maps)
	amount := maps[0]["amount"]
	return nodes, amount
}

func (this PqCsSimuLibrary) GetFinishRateBySimuId(id interface{}) interface{} {
	model := GetSlaveDb()
	var nodes []orm.Params
	model.Raw(`
		SELECT ceil(sum(t2.is_answered = 1) / count(id) * 100) as finish_rate  from pq_cs_simu_item_connection t2 
        where t2.pq_cs_test_simu_library_id =?  GROUP BY t2.pq_cs_test_simu_library_id
    `,id).Values(&nodes)
	if len(nodes) > 0 {
		return nodes[0]["finish_rate"]
	}else{
		return "0"
	}
}